package com.gitee.netty.socket_demo;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 开发人员   YooLin1c
 * 编写日期   2018/7/21
 * 联系邮箱   401664157@qq.com
 * 作用描述
 */
@Slf4j
@AllArgsConstructor
public class ClientHandler {
    private static final int MAX_DATA_LENGTH = 1024;
    private final Socket socket;

    public void start() {
        log.info("检测到新客户端连接接入");
        // 为每个客户端都创建一个线程，防止客户端的读写IO被阻塞而影响新客户端连接的方法执行
        new Thread(this::doStart).start();
    }

    private void doStart() {
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            while (true) {
                byte[] buffer = new byte[MAX_DATA_LENGTH];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    String message = new String(buffer, 0, len);
                    log.info("接收到客户端传来的消息：{}", message);
                    outputStream.write("got n ".getBytes());
                }
            }
        } catch (IOException e) {
            log.error("接收客户端数据失败", e);
        }
    }
}
